package com.lry.jvm.instructions.base;

import lombok.Getter;
import lombok.Setter;

import java.nio.ByteBuffer;

@Getter
@Setter
public class BytecodeReader {
    private byte[] code;

    private int pc;
    public BytecodeReader(){}
    public BytecodeReader(byte[] code, int pc) {
        this.code = code;
        this.pc = pc;
    }

    public BytecodeReader reset(byte[] code, int pc) {
        this.code = code;
        this.pc = pc;
        return this;
    }

    public byte read8(){
        byte b = code[pc++];
        return b;
    }

    public short read16(){
        byte b1 = code[pc++];
        //低位必须都搞成正数
        int b2 = add256(code[pc++]);
        return (short) (b1 << 8| b2);
    }

    public int read32() {
        byte b1 = code[pc++];
        //低位必须都搞成正数
        int b2 = add256(code[pc++]);
        int b3 = add256(code[pc++]);
        int b4 = add256(code[pc++]);
        return b1 << 24 | b2 << 16 | b3 << 8 | b4;
    }

    public int add256(byte b){
        if(b>=0){
            return b;
        }
        return b+256;
    }


    public static void main(String[] args) {
        byte b1 = 0;
        byte b2 = -6;
        System.out.println((short) (b1 << 8 | b2));
    }
    public int[] readInt32s(int length) {
        int[] ints = new int[length];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = read32();
        }
        return ints;
    }

    public void skipPadding(){
        while (pc % 4 != 0) {
            read8();
        }
    }
}
